import express from 'express';
import { query, param, body, validationResult } from 'express-validator';
import { User, UserQuota, Question, Order, UserLog, RedeemCode, Domain, Expert } from '../models/index.js';
import { authenticateAdmin } from '../middleware/auth.js';
import { catchAsync, BusinessError, NotFoundError } from '../middleware/errorHandler.js';
import { success, paginated } from '../utils/response.js';
import { Op } from 'sequelize';

const router = express.Router();

// 管理员接口 - 获取用户列表
router.get('/admin/list',
  authenticateAdmin,
  [
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间'),
    query('keyword').optional().isLength({ max: 100 }).withMessage('关键词不能超过100个字符'),
    query('is_active').optional().custom((value) => {
      if (value === null || value === undefined || value === '') return true;
      if (value === 'true' || value === 'false' || value === true || value === false) return true;
      throw new Error('状态参数必须是布尔值');
    })
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { page = 1, limit = 20, keyword, is_active } = req.query;
    const where = {};

    if (keyword) {
      where.phone = { [Op.like]: `%${keyword}%` };
    }

    if (is_active !== undefined) {
      where.is_active = is_active === 'true';
    }
    
    const result = await User.findAndCountAll({
      where,
      attributes: { exclude: ['password'] },
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: (parseInt(page) - 1) * parseInt(limit)
    });
    
    res.json(paginated(result.rows, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: result.count,
      pages: Math.ceil(result.count / parseInt(limit))
    }, '获取用户列表成功'));
  })
);

// 管理员接口 - 获取用户统计数据
router.get('/admin/stats',
  authenticateAdmin,
  catchAsync(async (req, res) => {
    try {
      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
      const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);

      // 总用户数
      const totalUsers = await User.count() || 0;

      // 活跃用户数（最近30天有登录的）
      const activeUsers = await User.count({
        where: {
          last_login_at: {
            [Op.gte]: thirtyDaysAgo
          }
        }
      }) || 0;

      // 今日新增用户数
      const todayNewUsers = await User.count({
        where: {
          created_at: {
            [Op.gte]: today
          }
        }
      }) || 0;

      // 本月新增用户数
      const monthNewUsers = await User.count({
        where: {
          created_at: {
            [Op.gte]: monthStart
          }
        }
      }) || 0;

      res.json(success({
        total: totalUsers,
        active: activeUsers,
        todayNew: todayNewUsers,
        monthNew: monthNewUsers
      }, '获取用户统计数据成功'));
    } catch (error) {
      // 即使查询出错，也返回0填充的数据，确保前端正常显示
      console.error('获取用户统计数据出错:', error);
      res.json(success({
        total: 0,
        active: 0,
        todayNew: 0,
        monthNew: 0
      }, '获取用户统计数据成功'));
    }
  })
);

// 管理员接口 - 获取可用兑换码列表（最新50个）
router.get('/admin/available-redeem-codes',
  authenticateAdmin,
  catchAsync(async (req, res) => {
    const redeemCodes = await RedeemCode.findAll({
      where: {
        is_used: false,
        [Op.or]: [
          { expires_at: null },
          { expires_at: { [Op.gt]: new Date() } }
        ]
      },
      include: [
        { association: 'domain', attributes: ['id', 'name'] },
        { association: 'expert', attributes: ['id', 'nickname'] }
      ],
      order: [['created_at', 'DESC']],
      limit: 50
    });

    res.json(success({
      redeemCodes
    }, '获取可用兑换码列表成功'));
  })
);

// 管理员接口 - 获取用户详情
router.get('/admin/:id',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('用户ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const { id } = req.params;
    
    const user = await User.findByPk(id, {
      attributes: { exclude: ['password'] },
      include: [
        {
          association: 'quotas',
          include: [
            { association: 'domain', attributes: ['id', 'name'] },
            { association: 'expert', attributes: ['id', 'nickname'] }
          ]
        }
      ]
    });
    
    if (!user) {
      throw new NotFoundError('用户不存在');
    }
    
    res.json(success({
      user
    }, '获取用户详情成功'));
  })
);

// 管理员接口 - 获取用户订单列表
router.get('/admin/:id/orders',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('用户ID必须是正整数'),
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间')
  ],
  catchAsync(async (req, res) => {
    const { id } = req.params;
    const { page = 1, limit = 20 } = req.query;
    
    const result = await Order.getUserOrders(id, {
      page: parseInt(page),
      limit: parseInt(limit)
    });
    
    res.json(paginated(result.rows, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: result.count,
      pages: Math.ceil(result.count / parseInt(limit))
    }, '获取用户订单成功'));
  })
);

// 管理员接口 - 获取用户问答记录
router.get('/admin/:id/questions',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('用户ID必须是正整数'),
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间')
  ],
  catchAsync(async (req, res) => {
    const { id } = req.params;
    const { page = 1, limit = 20 } = req.query;
    
    const result = await Question.getUserQuestions(id, {
      page: parseInt(page),
      limit: parseInt(limit)
    });
    
    res.json(paginated(result.rows, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: result.count,
      pages: Math.ceil(result.count / parseInt(limit))
    }, '获取用户问答记录成功'));
  })
);

// 管理员接口 - 获取用户日志
router.get('/admin/:id/logs',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('用户ID必须是正整数'),
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间'),
    query('log_type').optional().isIn(['register', 'login', 'redeem']).withMessage('日志类型参数无效')
  ],
  catchAsync(async (req, res) => {
    const { id } = req.params;
    const { page = 1, limit = 20, log_type } = req.query;

    const result = await UserLog.getUserLogs(id, {
      page: parseInt(page),
      limit: parseInt(limit),
      logType: log_type
    });

    res.json(paginated(result.rows, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: result.count,
      pages: Math.ceil(result.count / parseInt(limit))
    }, '获取用户日志成功'));
  })
);

// 管理员接口 - 给用户兑换兑换码
router.post('/admin/:id/redeem',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('用户ID必须是正整数'),
    body('redeem_code_id').isInt({ min: 1 }).withMessage('兑换码ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { id: userId } = req.params;
    const { redeem_code_id } = req.body;
    const adminId = req.admin.id;

    // 验证用户是否存在
    const user = await User.findByPk(userId);
    if (!user) {
      throw new NotFoundError('用户不存在');
    }

    // 验证兑换码是否存在且可用
    const redeemCode = await RedeemCode.findByPk(redeem_code_id, {
      include: [
        { association: 'domain', attributes: ['id', 'name'] },
        { association: 'expert', attributes: ['id', 'nickname'] }
      ]
    });

    if (!redeemCode) {
      throw new NotFoundError('兑换码不存在');
    }

    if (!redeemCode.canRedeem()) {
      throw new BusinessError('兑换码已使用或已过期');
    }

    // 验证目标是否有效
    if (redeemCode.quota_type === 'domain' && redeemCode.target_id) {
      const domain = await Domain.findByPk(redeemCode.target_id);
      if (!domain || !domain.is_enabled) {
        throw new BusinessError('兑换码对应的领域不存在或已禁用');
      }
    } else if (redeemCode.quota_type === 'expert' && redeemCode.target_id) {
      const expert = await Expert.findByPk(redeemCode.target_id);
      if (!expert || !expert.is_enabled) {
        throw new BusinessError('兑换码对应的专家不存在或已禁用');
      }
    }

    // 使用兑换码
    await redeemCode.redeem(userId);

    // 创建用户额度
    const userQuota = await UserQuota.createQuota({
      user_id: userId,
      quota_type: redeemCode.quota_type,
      target_id: redeemCode.target_id,
      total_count: redeemCode.redeem_count,
      used_count: 0,
      remaining_count: redeemCode.redeem_count,
      expires_at: redeemCode.expires_at
    });

    // 记录兑换日志
    await UserLog.createRedeemLog(userId, redeemCode.id, req.ip, req.get('User-Agent'), {
      admin_id: adminId,
      redeem_code: redeemCode.code,
      quota_type: redeemCode.quota_type,
      redeem_count: redeemCode.redeem_count
    });

    res.json(success({
      userQuota,
      redeemCode: {
        id: redeemCode.id,
        code: redeemCode.code,
        quota_type: redeemCode.quota_type,
        redeem_count: redeemCode.redeem_count
      }
    }, '兑换码兑换成功'));
  })
);

export default router;
